import React, { useState, useEffect, useCallback } from 'react';
import { 
  Card, 
  Typography, 
  Form, 
  Input, 
  Button, 
  Select, 
  message, 
  Tabs, 
  Space,
  Divider,
  Modal
} from 'antd';
import { 
  SettingOutlined, 
  UserOutlined, 
  LockOutlined, 
  ProfileOutlined 
} from '@ant-design/icons';
import { authAPI } from '../../services/AuthService';
import '../../styles/Settings.css';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const Settings = () => {
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState(null);
  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [preferencesForm] = Form.useForm();
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);

  const fetchUserInfo = useCallback(async () => {
    try {
      const [userResponse, profileResponse] = await Promise.all([
        authAPI.getCurrentUser(),
        authAPI.getUserProfileData()
      ]);
      
      // 处理用户基本信息
      const userData = userResponse.data;
      setUserInfo(userData);
      profileForm.setFieldsValue({
        username: userData.username,
        nickname: userData.nickname,
        bio: userData.bio,
        email: userData.email
      });
      
      // 处理用户画像数据
      const profileData = profileResponse || {};
      
      // 将 emotional_preferences 从字典格式转换为数组格式
      const emotionalPreferencesArray = profileData.emotional_preferences ? 
        Object.keys(profileData.emotional_preferences).filter(key => profileData.emotional_preferences[key]) : [];
      
      preferencesForm.setFieldsValue({
        age_group: profileData.age_group || null,
        gender: profileData.gender || null,
        location: profileData.location || null,
        favorite_genres: profileData.favorite_genres || [],
        emotional_preferences: emotionalPreferencesArray,
        favorite_actors: profileData.favorite_actors || [],
        favorite_directors: profileData.favorite_directors || [],
        mood_history: profileData.mood_history || []
      });
    } catch (error) {
      console.error('获取用户信息失败:', error);
      message.error('获取用户信息失败: ' + (error.response?.data?.detail || error.message));
    }
  }, [profileForm, preferencesForm]);

  // 获取用户信息
  useEffect(() => {
    fetchUserInfo();
  }, [fetchUserInfo]);

  // 更新用户资料
  const handleProfileUpdate = async (values) => {
    setLoading(true);
    try {
      await authAPI.updateProfile(values);
      message.success('资料更新成功');
      fetchUserInfo(); // 重新获取用户信息
    } catch (error) {
      console.error('更新用户资料失败:', error);
      message.error('更新失败：' + (error.response?.data?.detail || '请稍后重试'));
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handlePasswordChange = async (values) => {
    setLoading(true);
    try {
      await authAPI.changePassword({
        old_password: values.oldPassword,
        new_password: values.newPassword,
        confirm_password: values.confirmPassword
      });
      message.success('密码修改成功');
      setPasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (error) {
      console.error('修改密码失败:', error);
      message.error('修改失败：' + (error.response?.data?.detail || '请稍后重试'));
    } finally {
      setLoading(false);
    }
  };

  // 保存偏好设置
  const handlePreferencesSave = async (values) => {
    setLoading(true);
    try {
      // 处理 emotional_preferences 字段，将数组转换为字典格式
      const processedValues = {
        ...values,
        emotional_preferences: values.emotional_preferences ? 
          values.emotional_preferences.reduce((acc, pref) => {
            acc[pref] = true;
            return acc;
          }, {}) : null
      };
      
      await authAPI.updateUserProfileData(processedValues);
      message.success('偏好设置保存成功！');
      // 重新获取用户信息以确保数据同步
      fetchUserInfo();
    } catch (error) {
      console.error('保存偏好设置失败:', error);
      message.error('保存偏好设置失败: ' + (error.response?.data?.detail || error.message));
    } finally {
      setLoading(false);
    }
  };

  const tabItems = [
    {
      key: 'profile',
      label: (
        <span>
          <UserOutlined />
          基本信息
        </span>
      ),
      children: (
        <Card className="profile-card">
          <Form
            form={profileForm}
            layout="vertical"
            onFinish={handleProfileUpdate}
            className="profile-form"
          >
            <Title level={4} className="section-title">个人信息</Title>
            <Form.Item
              label="用户名"
              name="username"
            >
              <Input 
                value={userInfo?.username} 
                disabled 
                placeholder="用户名（不可修改）"
              />
            </Form.Item>
            
            <Form.Item
              label="邮箱"
              name="email"
            >
              <Input 
                value={userInfo?.email} 
                disabled 
                placeholder="邮箱（不可修改）"
              />
            </Form.Item>
            
            <Form.Item
              label="昵称"
              name="nickname"
              rules={[
                { max: 50, message: '昵称不能超过50个字符' }
              ]}
            >
              <Input placeholder="请输入昵称" />
            </Form.Item>
            
            <Form.Item
              label="个人简介"
              name="bio"
              rules={[
                { max: 200, message: '个人简介不能超过200个字符' }
              ]}
            >
              <TextArea 
                rows={4} 
                placeholder="请输入个人简介" 
                showCount
                maxLength={200}
              />
            </Form.Item>
            
            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  className="save-button"
                >
                  保存修改
                </Button>
                <Button 
                  onClick={() => setPasswordModalVisible(true)}
                  icon={<LockOutlined />}
                  className="password-button"
                >
                  修改密码
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      )
    },
    {
      key: 'preferences',
      label: (
        <span>
          <ProfileOutlined />
          偏好设置
        </span>
      ),
      children: (
        <Card className="preferences-card">
          <Form
            form={preferencesForm}
            layout="vertical"
            onFinish={handlePreferencesSave}
            className="preferences-form"
          >
            <Title level={4} className="section-title">用户画像设置</Title>
            <Form.Item
              label="年龄段"
              name="age_group"
            >
              <Select placeholder="请选择年龄段">
                <Option value="teenager">青少年</Option>
                <Option value="young_adult">青年</Option>
                <Option value="middle_aged">中年</Option>
                <Option value="senior">老年</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              label="性别"
              name="gender"
            >
              <Select placeholder="请选择性别">
                <Option value="male">男</Option>
                <Option value="female">女</Option>
                <Option value="other">其他</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              label="地区"
              name="location"
            >
              <Input placeholder="请输入所在地区" />
            </Form.Item>
            
            <Form.Item
              label="喜好类型"
              name="favorite_genres"
            >
              <Select 
                mode="multiple" 
                placeholder="请选择喜欢的影视类型"
                className="genre-select"
              >
                <Option value="动作">动作</Option>
                <Option value="冒险">冒险</Option>
                <Option value="动画">动画</Option>
                <Option value="喜剧">喜剧</Option>
                <Option value="犯罪">犯罪</Option>
                <Option value="纪录">纪录</Option>
                <Option value="剧情">剧情</Option>
                <Option value="家庭">家庭</Option>
                <Option value="奇幻">奇幻</Option>
                <Option value="历史">历史</Option>
                <Option value="恐怖">恐怖</Option>
                <Option value="音乐">音乐</Option>
                <Option value="悬疑">悬疑</Option>
                <Option value="爱情">爱情</Option>
                <Option value="科幻">科幻</Option>
                <Option value="电视电影">电视电影</Option>
                <Option value="惊悚">惊悚</Option>
                <Option value="战争">战争</Option>
                <Option value="西部">西部</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              label="情感偏好"
              name="emotional_preferences"
            >
              <Select 
                mode="multiple" 
                placeholder="请选择情感偏好"
                className="emotion-select"
              >
                <Option value="快乐">快乐</Option>
                <Option value="悲伤">悲伤</Option>
                <Option value="刺激">刺激</Option>
                <Option value="放松">放松</Option>
                <Option value="励志">励志</Option>
                <Option value="深思">深思</Option>
                <Option value="浪漫">浪漫</Option>
                <Option value="冒险">冒险</Option>
                <Option value="神秘">神秘</Option>
                <Option value="怀旧">怀旧</Option>
                <Option value="振奋">振奋</Option>
                <Option value="忧郁">忧郁</Option>
                <Option value="幽默">幽默</Option>
                <Option value="紧张">紧张</Option>
                <Option value="平静">平静</Option>
                <Option value="戏剧性">戏剧性</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              label="喜欢的演员"
              name="favorite_actors"
            >
              <Select 
                mode="tags" 
                placeholder="请输入喜欢的演员姓名"
                className="tag-select"
                tokenSeparators={[',']}
              >
              </Select>
            </Form.Item>
            
            <Form.Item
              label="喜欢的导演"
              name="favorite_directors"
            >
              <Select 
                mode="tags" 
                placeholder="请输入喜欢的导演姓名"
                className="tag-select"
                tokenSeparators={[',']}
              >
              </Select>
            </Form.Item>
            
            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                className="save-preferences"
              >
                保存偏好设置
              </Button>
            </Form.Item>
          </Form>
        </Card>
      )
    }
  ];

  return (
    <div className="settings-container">
      <Title level={2} className="settings-header">
        <SettingOutlined className="icon-settings"/> 设置
      </Title>
      
      <Tabs 
        defaultActiveKey="profile" 
        items={tabItems}
        className="settings-tabs"
      />
      
      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        footer={null}
        destroyOnClose
        className="password-modal"
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
          className="password-form"
        >
          <Form.Item
            label="当前密码"
            name="oldPassword"
            rules={[
              { required: true, message: '请输入当前密码' }
            ]}
          >
            <Input.Password placeholder="请输入当前密码" />
          </Form.Item>
          
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              })
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" />
          </Form.Item>
          
          <Form.Item className="password-actions">
            <Space>
              <Button 
                onClick={() => {
                  setPasswordModalVisible(false);
                  passwordForm.resetFields();
                }}
                className="cancel-button"
              >
                取消
              </Button>
              <Button 
                // type="primary" 
                htmlType="submit" 
                loading={loading}
                className="confirm-button"
              >
                确认修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Settings;